/**
 * 存储整型数据的单向链表的实现
 */
public class MyLinkedList{
	//头节点，尾节点
	private Node head,tail;
	/**
	 * 初始化链表
	 */
	public MyLinkedList(){
		head = tail = null;
	}
	/**
	 * 增加头节点
	 */
	public void addToHead(int data){
		head = new Node(data,head);
		if(tail == null){
			tail = head;
		}
	}
	/**
	 * 增加尾节点
	 */
	public void addToTail(int data){
		if(isEmpty()){
			tail.next = new Node(data);
			tail = tail.next;
		}else{
			head = tail = new Node(data);
		}
	}
	/**
	 * 删除头部节点
	 */
	public int deletFromHead(){
		int data = head.data;
		if(isEmpty()){
			return 0;
		}
		if(head == tail){//只有一个节点
			head = tail = null;
		}else{
			head = head.next;
		}
		return data;
	}
	/**
	 * 删除尾节点
	 */
	public int deletFromTail(){
		int data = tail.data;
		if(isEmpty()){
			return 0;
		}
		if(head == tail){//只有一个节点
			head = tail = null;
		}else{
			Node node;
			for (node = head;node.next != tail ;node = node.next);
			tail = node;
			tail.next = null;
		}
		return data;
	}
	/**
	 * 打印全部数据
	 */
	public void printAll(){
		for (Node temp = head;temp != null ;temp = temp.next ) {
			System.out.print(temp.data+"---");
		}
		System.out.println();
	}
	/**
	 * 链表中是否存在数据data
	 */
	public boolean isInList(int data){
		Node temp;
		for (temp = head;head != null && temp.data != data ;temp = temp.next ) ;
		return temp != null;
	}
	/**
	 * 删除包含某个特定数据的指定节点
	 */
	public void delete(int data){
		if(!isEmpty()){
			if(head == tail && data == head.data){
				head = tail = null;
			}else if(data == head.data){
				head = head.next;
			}else{//要删除的数据不在头节点
				Node pred,temp;
				for (pred = head,temp = head.next;temp != null && temp.data != data;pred = pred.next,temp = temp.next) ;
				if(temp != null){
					pred.next = temp.next;
					if(temp == tail){
						tail = pred;
					}
				}
			}
		}
	}
	/**
	 * 判断链表是否为空
	 */
	public boolean isEmpty(){
		return head == null;
	}
	/**
	 * 测试
	 */
	public static void main(String[] args) {
		MyLinkedList list = new MyLinkedList();	
		list.addToHead(1);
		list.addToHead(2);
		list.addToHead(3);
		list.addToHead(4);
		System.out.println(list.isInList(1));
		list.printAll();
	}
	/**
	 * 节点类
	 */
	class Node{	
		private int data;//数据域
		private Node next;//指针域

		public Node(int data,Node node){
			this.data = data;
			this.next = node;
		}

		public Node(int data){
			this(data,null);	
		}
	}
}